package tool;

import java.sql.SQLException;
import java.sql.Statement;

public class GetInfoByPath {
	public static String get_currentDirId_by_path(Statement state,
			String userName, String masterPath) throws SQLException {
		// debug
		// System.out.println(String.format("userDataStoreApi.java: \tfileName:%s \tmasterPath:%s",
		// fileName, masterPath));
		String currentDirId = null;
		if (masterPath.startsWith("/") == false)
			return null;
		String userHomeDirId = MysqlApi.get_home_dir_id_by_user_name(state,
				userName);
		// debug
		// System.out.println(String.format("userHomeDirId = %s(userDataStoreApi.java)",
		// userHomeDirId));
		if (userHomeDirId == null) {
			System.out.println("mysql dont exit user_name:" + userName);
			return null;
		}

		String subMasterPath = masterPath.substring(1);
		String userHomeDirName;
		int mark;
		if ((mark = subMasterPath.indexOf('/')) != -1) {
			userHomeDirName = subMasterPath.substring(0, mark);

			// debug
			// System.out.println(String.format("userDataStoreApi.java:\t userHomeDirName = %s",
			// userHomeDirName));
			if (userHomeDirName.equals(userName) == false) {
				System.out.println("masterPath root not equel userName error: " + masterPath);
				return null;
			}

			// debug
			System.out.println(String.format("userHomeDirId = %s   subMasterPath.substring(mark)=%s(userDataStoreApi.java)",
					userHomeDirId,  subMasterPath.substring(mark)));
			if ((currentDirId = MysqlApi.get_current_dir_id_by_path(state,
					userHomeDirId, subMasterPath.substring(mark))) == null) {
				System.out.println("masterPath error: " + masterPath);
				return null;
			}
		} else {
			// debug
			// System.out.println(String.format("userDataStoreApi.java: \tsubMasterPath = [%s]   userName=[%s]",
			// subMasterPath, userName));
			if (subMasterPath.equals(userName) == false) {
				// debug
				 System.out.println(String.format("subMasterPath = [%s]   userName=[%s](GetInfoByPath.java)", subMasterPath, userName));
				System.out.println("masterPath error: " + masterPath);
				return null;
			}
			currentDirId = userHomeDirId;
		}
		return currentDirId;
	}

	static public String get_fileName_by_path(String masterPath, int lastMark) {
		String fileName = masterPath.substring(lastMark + 1);
		if (IsLegalName.Is_legal_name(fileName) == false) {
			System.out.println("fileName is not legal : " + fileName);
			return null;
		}
		return fileName;
	}
}
